package com.syg.servlet02;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * 文件下载
 *          文件名是中文的处理方式：使用URLEncoder.encode(fileName, "字符编码")
 */
@WebServlet("/downloadChinese")
public class _04_DownLoadFile_Chinese extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.获取要下载的绝对路径
        String realPath = this.getServletContext().getRealPath("/Images/许可证.png");
        //2.获取要下载的文件名
        String fileName = realPath.substring(realPath.lastIndexOf("\\")+1);
        //3.设置content-disposition响应头控制浏览器以下载的形式打开文件
        resp.setHeader("content-disposition", "attachment;filename="+ URLEncoder.encode(fileName,"utf-8"));
        //4.获取要下载文件的输入流
        InputStream in = new FileInputStream(realPath);
        //5.创建数据缓冲区
        byte[] bufferByte = new byte[1024];
        //6.通过response对象获取OutputStream流
        OutputStream respOut = resp.getOutputStream();
        //7.将FileInputStream流写入到buffer缓冲区
        int len = 0;
        while ((len=in.read(bufferByte))>0){
            //8.使用OutputStream将缓冲区的数据输出到客户端浏览器
            respOut.write(bufferByte,0,len);
        }
        in.close();
    }
}
